package com.zhuyi.broadcast.controller;

import com.zhuyi.broadcast.pojo.domain.Device;
import com.zhuyi.broadcast.service.DeviceService;
import com.zhuyi.common.core.controller.BaseController;
import com.zhuyi.common.core.domain.AjaxResult;
import com.zhuyi.common.core.page.TableDataInfo;
import com.zhuyi.common.utils.DateUtils;
import com.zhuyi.common.utils.SecurityUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.*;

/**
 * <p>
 * 设备Controller
 * </p>
 *
 * @author 代永健
 * @since 2024-12-23
 */
@Slf4j
@RestController
@RequestMapping("/broadcast/device")
public class DeviceController extends BaseController {

    @Autowired
    private DeviceService deviceService;

    /**
     * 查询设备（列表）
     */
    @GetMapping("/list")
    public TableDataInfo list(@RequestParam(required = false) String searchKey)
    {
        List<Device> list = deviceService.list(searchKey);
        return getDataTable(list);
    }

    /**
     * 添加设备
     */
    @PostMapping("/save")
    public AjaxResult saveDevice(@RequestBody @Valid Device device) {
        try {
            device.setUpdateBy(SecurityUtils.getLoginUser().getUser().getNickName());
            device.setCreateBy(SecurityUtils.getLoginUser().getUser().getNickName());
            device.setCreateTime(DateUtils.getNowDate());
            device.setUpdateTime(DateUtils.getNowDate());
            deviceService.save(device);
            return success(device);
        } catch (Exception e) {
            log.error("[DeviceController::saveDevice]创建设备，错误消息: {}", e.getMessage());
            e.fillInStackTrace();
        }
        return error("创建设备错误");
    }

    /**
     * 更新设备
     */
    @PutMapping("/{deviceId}")
    public AjaxResult updateDevice(@PathVariable Long deviceId,
                                   @RequestBody @Valid Device device) {
        try {
            device.setId(deviceId);
            device.setUpdateBy(SecurityUtils.getLoginUser().getUser().getNickName());
            device.setUpdateTime(DateUtils.getNowDate());
            deviceService.updateById(device);
            return success(device);
        } catch (Exception e) {
            log.error("[DeviceController::updateDevice]更新诊室设备出现错误，错误消息: {}", e.getMessage());
            e.fillInStackTrace();
        }
        return error("更新诊室设备出现错误");
    }

    /**
     * 删除设备
     */
    @DeleteMapping("/{deviceId}")
    public AjaxResult deleteDevice(@PathVariable Long deviceId) {
        try {
            return success(deviceService.removeById(deviceId));
        } catch (Exception e) {
            log.error("[DeviceController::deleteDevice]删除设备，错误消息: {}", e.getMessage());
            e.fillInStackTrace();
        }
        return error("删除设备错误");
    }



    /**
     * 添加轮播计划(向设备)
     */
    @PostMapping("/schedule")
    public AjaxResult addScheduleToDevice(@RequestParam Long deviceId,
                                          @RequestParam Long scheduleId) {
        boolean result = deviceService.addScheduleToDevice(deviceId, scheduleId);
        if (result) {
            return success("发送成功");
        } else {
            return error("发送失败");
        }
    }

    /**
     * 删除轮播计划（从设备）
     */
    @DeleteMapping("/schedule")
    public AjaxResult deleteScheduleFromDevice(@RequestParam Long deviceId,
                                               @RequestParam Long scheduleId) {
        boolean result = deviceService.deleteScheduleFromDevice(deviceId, scheduleId);
        if (result) {
            return success("删除成功");
        } else {
            return error("删除失败");
        }
    }

//    @GetMapping(value = "/heartbeat/connect")
//    public AjaxResult setHeartbeat(@RequestParam(required = false) String deviceCode) {
//        Map<String, Object> result = new HashMap<>();
//        String ipAddress = IpUtils.getIpAddr();
//        String sseId = ObjectUtils.isNotEmpty(deviceCode) ? deviceCode : ipAddress;
//        log.info("current device heartbeat: {}", sseId);
//        List<BcDevice> devices = deviceService.listByCode(Arrays.asList(new String[]{sseId}));
//        String templateUrl = "";
//        log.info("current device heartbeat，select by code{}", devices.size());
//        if (ObjectUtils.isNotEmpty(devices)) {
//            BcDevice device = devices.get(0);
//            device.setLastConnectTime(new Date());
//            deviceService.updateById(device);
//            log.info("current device heartbeat, update connect time success");
//
//            try {
//                JSONObject currentSchedule = null;
//                List<BcSchedule> listSchedule = deviceScheduleService.listScheduleByDeviceId(device.getId());
//                log.info("current device heartbeat, select device schedules:{}", listSchedule.size());
//                if (ObjectUtils.isNotEmpty(listSchedule)) {
//                    listSchedule.sort(new Comparator<BcSchedule>() {
//                        @Override
//                        public int compare(BcSchedule p1, BcSchedule p2) {
//                            return p2.getUpdateTime().compareTo(p1.getUpdateTime());
//                        }
//                    });
//                    long currentTime = new Date().getTime() / 1000;
//                    for (BcSchedule schedule : listSchedule) {
//                        if (ObjectUtils.isNotEmpty(schedule.getConfig())) {
//                            JSONArray configArr = JSONArray.parseArray(schedule.getConfig());
//                            for (int i = 0; i < configArr.size(); i++) {
//                                JSONObject obj = configArr.getJSONObject(i);
//                                Integer startTime = 0;
//                                Integer endTime = 0;
//                                if (ObjectUtils.isNotEmpty(obj.get("startTime"))) {
//                                    startTime = (Integer) obj.get("startTime");
//                                }
//                                if (ObjectUtils.isNotEmpty(obj.get("endTime"))) {
//                                    endTime = (Integer) obj.get("endTime");
//                                }
//                                if (startTime <= currentTime && currentTime <= endTime) {
//                                    currentSchedule = obj;
//                                    break;
//                                }
//                            }
//                            if (ObjectUtils.isNotEmpty(currentSchedule)) {
//                                break;
//                            }
//                        }
//                    }
//                    if (ObjectUtils.isNotEmpty(currentSchedule)) {
//                        templateUrl = configService.selectConfigByKey("sys.web.baseurl") + "/preview.html?templateId=" + currentSchedule.get("templateId") + "&t=" + new Date().getTime();
//                        ;
//                    }
//                    log.info("current device heartbeat, get schedule template url from schedule:{}", templateUrl);
//                }
//
//                if (ObjectUtils.isEmpty(templateUrl)) {
//                    String display = device.getConfig();
//                    JSONObject obj = JSONObject.parseObject(display);
//                    if (ObjectUtils.isNotEmpty(obj.get("templateId"))) {
//                        templateUrl = configService.selectConfigByKey("sys.web.baseurl") + "/preview.html?templateId=" + obj.get("templateId") + "&t=" + new Date().getTime();
//                    }
//                    log.info("current device heartbeat, get schedule template url from config:{}", templateUrl);
//                }
//            } catch (Exception ex) {
//            }
//        }
//        log.info("current device heartbeat, get client page url:{}", templateUrl);
//        result.put("clientPageUrl", templateUrl);
//        result.put("device", ObjectUtils.isEmpty(devices) ? null : devices.get(0));
//        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//        result.put("serverTime", new Date().getTime());
//        return success(result);
//    }
}
